<!--
  通信方式完整示例
  
  演示广播通信和自定义事件的实际使用场景
-->

<template>
  <div class="communication-example">
    <div class="header">
      <h2>🔄 通信方式实战演示</h2>
      <p class="subtitle">广播通信 vs 自定义事件的实际应用</p>
    </div>

    <div class="demo-sections">
      
      <!-- 广播通信示例：多窗口状态同步 -->
      <div class="demo-section">
        <h3>📡 广播通信：多窗口状态同步</h3>
        <div class="scenario">
          <p><strong>场景：</strong>模拟电商应用的购物车同步</p>
          
          <div class="controls">
            <select v-model="selectedProduct" class="input">
              <option value="iphone">iPhone 15 Pro - ¥8999</option>
              <option value="macbook">MacBook Pro - ¥16999</option>
              <option value="airpods">AirPods Pro - ¥1899</option>
            </select>
            <button @click="addToCart" class="btn btn-success">添加到购物车</button>
            <button @click="clearCart" class="btn btn-warning">清空购物车</button>
          </div>

          <div class="cart-status">
            <h4>当前购物车状态：</h4>
            <div v-if="cartItems.length === 0" class="empty-cart">购物车为空</div>
            <div v-else class="cart-items">
              <div v-for="item in cartItems" :key="item.id" class="cart-item">
                {{ item.name }} - ¥{{ item.price }} x {{ item.quantity }}
              </div>
              <div class="cart-total">
                总计：¥{{ cartTotal }}
              </div>
            </div>
          </div>

          <div class="broadcast-log">
            <h4>广播消息日志：</h4>
            <div class="log-list">
              <div v-for="(log, index) in broadcastLogs" :key="index" class="log-item">
                <span class="log-time">{{ log.time }}</span>
                <span class="log-event">{{ log.event }}</span>
                <span class="log-data">{{ log.data }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 自定义事件示例：订单处理流程 -->
      <div class="demo-section">
        <h3>⚡ 自定义事件：订单处理流程</h3>
        <div class="scenario">
          <p><strong>场景：</strong>模拟订单处理的完整流程，多个模块协同工作</p>
          
          <div class="controls">
            <button @click="processOrder" class="btn btn-primary" :disabled="processing">
              {{ processing ? '处理中...' : '提交订单' }}
            </button>
            <button @click="clearOrderLogs" class="btn btn-secondary">清空日志</button>
          </div>

          <div class="order-process">
            <h4>订单处理进度：</h4>
            <div class="process-steps">
              <div v-for="step in orderSteps" :key="step.id" 
                   :class="['process-step', step.status]">
                <span class="step-icon">{{ step.icon }}</span>
                <span class="step-name">{{ step.name }}</span>
                <span class="step-status">{{ step.status }}</span>
              </div>
            </div>
          </div>

          <div class="event-log">
            <h4>事件处理日志：</h4>
            <div class="log-list">
              <div v-for="(log, index) in eventLogs" :key="index" class="log-item">
                <span class="log-time">{{ log.time }}</span>
                <span class="log-module">{{ log.module }}</span>
                <span class="log-message">{{ log.message }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 实际应用场景对比 -->
      <div class="demo-section">
        <h3>📊 使用场景对比</h3>
        <div class="comparison">
          <div class="comparison-item">
            <h4>🎯 广播通信适用场景</h4>
            <ul>
              <li>✅ 多窗口状态同步（购物车、用户信息）</li>
              <li>✅ 实时协作（多人编辑、聊天）</li>
              <li>✅ 系统级事件（主题切换、网络状态）</li>
              <li>✅ 窗口间数据共享</li>
            </ul>
          </div>
          
          <div class="comparison-item">
            <h4>⚡ 自定义事件适用场景</h4>
            <ul>
              <li>✅ 业务流程编排（订单处理、支付流程）</li>
              <li>✅ 模块解耦（插件系统、微前端）</li>
              <li>✅ 异步任务协调（文件上传、数据处理）</li>
              <li>✅ 状态机管理（游戏状态、应用状态）</li>
            </ul>
          </div>
        </div>
      </div>

    </div>

    <!-- 消息提示 -->
    <div v-if="message.text" :class="['message', message.type]">
      {{ message.text }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'

// 产品数据
const products = {
  iphone: { id: 'iphone', name: 'iPhone 15 Pro', price: 8999 },
  macbook: { id: 'macbook', name: 'MacBook Pro', price: 16999 },
  airpods: { id: 'airpods', name: 'AirPods Pro', price: 1899 }
}

// 响应式数据
const selectedProduct = ref('iphone')
const cartItems = ref<Array<{id: string, name: string, price: number, quantity: number}>>([])
const broadcastLogs = ref<Array<{time: string, event: string, data: string}>>([])

const processing = ref(false)
const orderSteps = ref([
  { id: 1, name: '验证订单', icon: '✅', status: 'pending' },
  { id: 2, name: '库存检查', icon: '📦', status: 'pending' },
  { id: 3, name: '处理支付', icon: '💳', status: 'pending' },
  { id: 4, name: '生成发票', icon: '📄', status: 'pending' },
  { id: 5, name: '安排配送', icon: '🚚', status: 'pending' },
  { id: 6, name: '发送通知', icon: '📧', status: 'pending' }
])
const eventLogs = ref<Array<{time: string, module: string, message: string}>>([])

const message = ref({ text: '', type: 'info' })

// 计算属性
const cartTotal = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

// 方法

/**
 * 添加到购物车 - 使用广播通信
 */
const addToCart = () => {
  const product = products[selectedProduct.value as keyof typeof products]
  
  // 检查是否已存在
  const existingItem = cartItems.value.find(item => item.id === product.id)
  if (existingItem) {
    existingItem.quantity++
  } else {
    cartItems.value.push({ ...product, quantity: 1 })
  }

  // 广播购物车更新消息
  const cartData = {
    action: 'add',
    product: product.name,
    totalItems: cartItems.value.reduce((sum, item) => sum + item.quantity, 0),
    totalAmount: cartTotal.value
  }

  window.api.broadcast.send('cart-updated', cartData)
  
  addBroadcastLog('cart-updated', `添加 ${product.name} 到购物车`)
  showMessage(`${product.name} 已添加到购物车`, 'success')
}

/**
 * 清空购物车
 */
const clearCart = () => {
  cartItems.value = []
  
  window.api.broadcast.send('cart-updated', {
    action: 'clear',
    totalItems: 0,
    totalAmount: 0
  })
  
  addBroadcastLog('cart-updated', '清空购物车')
  showMessage('购物车已清空', 'info')
}

/**
 * 处理订单 - 使用自定义事件
 */
const processOrder = async () => {
  if (cartItems.value.length === 0) {
    showMessage('购物车为空，无法提交订单', 'warning')
    return
  }

  processing.value = true
  
  // 重置订单步骤状态
  orderSteps.value.forEach(step => step.status = 'pending')
  
  // 触发订单处理事件
  const orderData = {
    orderId: `ORDER-${Date.now()}`,
    items: cartItems.value,
    total: cartTotal.value,
    timestamp: new Date()
  }

  window.api.events.emit('order-submitted', orderData)
  
  // 模拟异步处理流程
  await processOrderSteps(orderData)
  
  processing.value = false
}

/**
 * 处理订单步骤
 */
const processOrderSteps = async (orderData: any) => {
  const steps = [
    { name: '验证订单', event: 'order-validated', delay: 1000 },
    { name: '库存检查', event: 'inventory-checked', delay: 1500 },
    { name: '处理支付', event: 'payment-processed', delay: 2000 },
    { name: '生成发票', event: 'invoice-generated', delay: 800 },
    { name: '安排配送', event: 'shipping-arranged', delay: 1200 },
    { name: '发送通知', event: 'notifications-sent', delay: 600 }
  ]

  for (let i = 0; i < steps.length; i++) {
    const step = steps[i]
    
    // 更新步骤状态为进行中
    orderSteps.value[i].status = 'processing'
    
    // 触发自定义事件
    window.api.events.emit(step.event, { ...orderData, step: i + 1 })
    
    // 模拟处理时间
    await new Promise(resolve => setTimeout(resolve, step.delay))
    
    // 更新步骤状态为完成
    orderSteps.value[i].status = 'completed'
  }

  // 订单完成
  window.api.events.emit('order-completed', orderData)
  showMessage('订单处理完成！', 'success')
}

/**
 * 添加广播日志
 */
const addBroadcastLog = (event: string, data: string) => {
  broadcastLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    event,
    data
  })
  
  // 只保留最近20条
  if (broadcastLogs.value.length > 20) {
    broadcastLogs.value.pop()
  }
}

/**
 * 添加事件日志
 */
const addEventLog = (module: string, message: string) => {
  eventLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    module,
    message
  })
  
  // 只保留最近20条
  if (eventLogs.value.length > 20) {
    eventLogs.value.pop()
  }
}

/**
 * 清空订单日志
 */
const clearOrderLogs = () => {
  eventLogs.value = []
  orderSteps.value.forEach(step => step.status = 'pending')
}

/**
 * 显示消息
 */
const showMessage = (text: string, type: string = 'info') => {
  message.value = { text, type }
  setTimeout(() => {
    if (message.value.text === text) {
      message.value.text = ''
    }
  }, 3000)
}

// 生命周期
onMounted(() => {
  // 监听广播消息
  window.api.broadcast.on('cart-updated', (data) => {
    addBroadcastLog('cart-updated-received', `收到购物车更新: ${JSON.stringify(data)}`)
  })

  // 监听自定义事件
  const eventHandlers = [
    'order-submitted',
    'order-validated', 
    'inventory-checked',
    'payment-processed',
    'invoice-generated',
    'shipping-arranged',
    'notifications-sent',
    'order-completed'
  ]

  eventHandlers.forEach(eventName => {
    window.api.events.on(eventName, (_data) => {
      const moduleName = eventName.split('-').map(word => 
        word.charAt(0).toUpperCase() + word.slice(1)
      ).join(' ')
      
      addEventLog(moduleName, `处理事件: ${eventName}`)
    })
  })

  showMessage('通信演示已就绪', 'success')
})

onUnmounted(() => {
  // 清理监听器
  window.api.broadcast.off('cart-updated')
})
</script>

<style scoped>
.communication-example {
  min-height: 100vh;
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.header h2 {
  color: #2c3e50;
  margin: 0;
  font-size: 2.2em;
}

.subtitle {
  color: #7f8c8d;
  margin: 5px 0 0 0;
  font-size: 1.1em;
}

.demo-sections {
  display: grid;
  gap: 40px;
}

.demo-section {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 30px;
  border-left: 4px solid #3498db;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

.demo-section h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.4em;
}

.scenario {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.scenario p {
  margin: 0 0 20px 0;
  color: #555;
  font-style: italic;
}

.controls {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 25px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 120px;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-success {
  background: linear-gradient(45deg, #2ecc71, #27ae60);
  color: white;
}

.btn-warning {
  background: linear-gradient(45deg, #f39c12, #e67e22);
  color: white;
}

.btn-primary {
  background: linear-gradient(45deg, #3498db, #2980b9);
  color: white;
}

.btn-secondary {
  background: linear-gradient(45deg, #95a5a6, #7f8c8d);
  color: white;
}

.input {
  padding: 10px 15px;
  border: 2px solid #bdc3c7;
  border-radius: 6px;
  font-size: 14px;
  min-width: 200px;
}

.cart-status, .order-process {
  background: #ecf0f1;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.cart-status h4, .order-process h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.empty-cart {
  color: #7f8c8d;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

.cart-items {
  display: grid;
  gap: 10px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background: white;
  border-radius: 4px;
  border-left: 3px solid #3498db;
}

.cart-total {
  font-weight: bold;
  font-size: 1.1em;
  text-align: right;
  color: #e74c3c;
  padding: 10px;
  background: white;
  border-radius: 4px;
  border-left: 3px solid #e74c3c;
}

.process-steps {
  display: grid;
  gap: 10px;
}

.process-step {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 12px;
  background: white;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.process-step.pending {
  border-left: 4px solid #bdc3c7;
  opacity: 0.6;
}

.process-step.processing {
  border-left: 4px solid #f39c12;
  background: #fff3cd;
  animation: pulse 1.5s infinite;
}

.process-step.completed {
  border-left: 4px solid #27ae60;
  background: #d4edda;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.02); }
}

.step-icon {
  font-size: 1.2em;
}

.step-name {
  flex: 1;
  font-weight: 500;
}

.step-status {
  font-size: 0.9em;
  color: #666;
  text-transform: uppercase;
}

.broadcast-log, .event-log {
  background: #2c3e50;
  color: white;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.broadcast-log h4, .event-log h4 {
  margin: 0 0 15px 0;
  color: #ecf0f1;
}

.log-list {
  max-height: 200px;
  overflow-y: auto;
  background: #34495e;
  border-radius: 4px;
  padding: 10px;
}

.log-item {
  display: flex;
  gap: 15px;
  padding: 8px;
  margin: 3px 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
}

.log-time {
  color: #95a5a6;
  min-width: 80px;
}

.log-event, .log-module {
  color: #3498db;
  font-weight: 600;
  min-width: 120px;
}

.log-data, .log-message {
  color: #ecf0f1;
  flex: 1;
}

.comparison {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.comparison-item {
  background: white;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.comparison-item h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.comparison-item ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.comparison-item li {
  padding: 8px 0;
  color: #555;
  border-bottom: 1px solid #ecf0f1;
}

.comparison-item li:last-child {
  border-bottom: none;
}

.message {
  padding: 12px 20px;
  border-radius: 6px;
  margin: 20px 0;
  font-weight: 500;
  border-left: 4px solid;
}

.message.info {
  background: #d1ecf1;
  color: #0c5460;
  border-color: #17a2b8;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border-color: #28a745;
}

.message.warning {
  background: #fff3cd;
  color: #856404;
  border-color: #ffc107;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comparison {
    grid-template-columns: 1fr;
  }
  
  .controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .input, .btn {
    width: 100%;
    min-width: unset;
  }
}
</style>
